<?php
/**
 * NetBiz Framework
 * Copyright (C) 20009 - 2010 NetBiz
 * 
 * All rights reserved.
 */

class FRM_Controller implements FRM_ACLInterface
{
	private $_acl = array();

	protected function checkAccess(FRM_UserInterface $user)
	{
		// Get the called resource based on the backtrace
		list($call) = debug_backtrace();
		$action = preg_replace('#Action$#','',$call['function']);

		// Get the role list for the operation
		$operation = get_class($this).'_'.$action;
		$roles_list = $this->getRolesForOperation($operation);

		return $user->hasRole($roles_list,FALSE);
	}

	/** From FRM_ACLInterface **/
	public function addPermission($operation,$roles)
	{
		if (!is_array($roles))
		{
			$roles = array($roles);
		}

		if (isset($this->_acl[$operation]))
		{
			$this->_acl[$operation] = array_merge($roles,$this->_acl[$operation]);
		}
		else
		{
			$this->_acl[$operation] = $roles;
		}
	}

	public function getRolesForOperation($operation)
	{
		return (isset($this->_acl[$operation]) ? $this->_acl[$operation] : array());
	}

	/**
	 * Method for XOAD to declare accessible methods
	 * Use reflection to publish only public methods
	 */
	public function xoadGetMeta()
	{
		$map = array();
		$r = new ReflectionClass(get_class($this));
		foreach($r->getMethods() as $m)
		{
			if ($m->isPublic() and !$m->isStatic() and !$m->isAbstract() and !$m->isConstructor()
				and !$m->isDestructor())
			{
				$name = $m->getName();
				$map[preg_replace('/(\w)Action$/','\1',$name)] = $name;
			}
		}

		$this->xoadMeta = new FRM_XOAD_Meta();
		$this->xoadMeta->setMethodsMap($map);
	}
}